import React from 'react';
import { Input, Select, message, Spin, Modal } from 'antd';
import Api from 'Utils/api';
import { connect } from 'react-redux';
import { BROWSER_MODE } from 'Constants/webConstants';
import { GCJ_TO_GPS84 } from 'Utils';
import { mapConfig } from 'Constants/config';
import TitleButton from 'Component/Page/Components/TitleButton';
import './marketInstitutionNavigation.scss';

const Option = Select.Option;
const OrganiseInfo = [
  {
    name: '福应所',
    phone: '0576-87755786',
    description: '福应市场监督管理所于2014年9月11日正式揭牌成立，前身为城东工商所。目前，全所有干部职工11人，管辖福应街道和广度乡（共43村6.5万余人口），经济户口5610余户。',
    photo: [{
      name: '张宇翔',
      icon: 'fys/1张宇翔.jpg'
    }, {
      name: '李小娇',
      icon: 'fys/2李小娇.jpg'
    }, {
      name: '张亚辉',
      icon: 'fys/3张亚辉.jpg'
    }, {
      name: '周时杨',
      icon: 'fys/4周时杨.jpg'
    }, {
      name: '胡青青',
      icon: 'fys/5胡青青.jpg'
    }, {
      name: '王雪萍',
      icon: 'fys/6王雪萍.jpg'
    }, {
      name: '林迪',
      icon: 'fys/7林迪.jpg'
    }, {
      name: '吴杭颖',
      icon: 'fys/8吴杭颖.jpg'
    }, {
      name: '丁锦满',
      icon: 'fys/9丁锦满.jpg'
    }, {
      name: '张伟利',
      icon: 'fys/10张伟利.jpg'
    }, {
      name: '吴福明',
      icon: 'fys/11吴福明.jpg'
    }],
  },
  {
    name: '安洲所',
    phone: '0576-87755614',
    description: '安洲市场监管所于2014年成立，管辖安洲街道和官路镇，总面积126.3平方公里，人口6.5万。辖区内经济户口主体总数5644家，其中食品经营户578家，各类医疗机构诊所53家，保化经营户100家。全所共11名干部职工，目前下辖官路高铁新城、安洲南、安洲北三个区块，今年以来探索推行“以块为主，条块结合”的区块监管执法模式，改变监管执法分离、只监管、不执法、监管单打一没有统筹的现状，正在向监管执法有机融合，在监管中执法、在执法中监管的统一体转变。',
    photo: [
      {
        name: '陈湖松',
        icon: 'azs/1陈湖松.jpg'
      },
      {
        name: '李展',
        icon: 'azs/2李展.jpg'
      },
      {
        name: '陈卫国',
        icon: 'azs/3陈卫国.jpg'
      },
      {
        name: '张永苏',
        icon: 'azs/4张永苏.jpg'
      },
      {
        name: '周益聪',
        icon: 'azs/周益聪.jpg'
      },
      {
        name: '张琦',
        icon: 'azs/张琦.jpg'
      },
      {
        name: '方逸平',
        icon: 'azs/方逸平.jpg'
      },
      {
        name: '王宇',
        icon: 'azs/王宇.jpg'
      },
      {
        name: '陈伟平',
        icon: 'azs/陈伟平.jpg'
      },
      {
        name: '陈美芬',
        icon: 'azs/陈美芬.jpg'
      },
      {
        name: '顾辉良',
        icon: 'azs/顾辉良.jpg'
      },
    ],
  },
  {
    name: '横溪分局',
    phone: '0576-87067047',
    description: '横溪市场监督管理分局于2014年9月11日正式揭牌成立，前身为横溪工商分局。目前，全所有干部职工10人，管辖横溪镇、埠头镇、湫山乡、溪港乡和安岭乡五个乡镇，经济户口4400余户。',
    photo: [{
      name: '陈洁',
      icon: 'hxs/陈洁.jpg'
    }, {
      name: '方颐',
      icon: 'hxs/工商局方颐.jpg'
    }, {
      name: '泮智辉',
      icon: 'hxs/工商局泮智辉.jpg'
    }, {
      name: '项优丽',
      icon: 'hxs/工商局项优丽.jpg'
    }, {
      name: '张立颖',
      icon: 'hxs/张立颖.jpg'
    }, {
      name: '徐和平',
      icon: 'hxs/徐和平.jpg'
    }, {
      name: '曹秀龙',
      icon: 'hxs/曹秀龙.jpg'
    }, {
      name: '王永东',
      icon: 'hxs/王永东.jpg'
    }, {
      name: '陈科',
      icon: 'hxs/陈科.jpg'
    }, {
      name: '骆潇帅',
      icon: 'hxs/骆潇帅.jpg'
    }],
  },
  {
    name: '南峰所',
    phone: '0576-87761108',
    description: '南峰市场监督管理所于2014年9月5日正式揭牌成立。目前，全所有干部职工12人，管辖南峰街道、步路乡和上张乡（共50村7.7万余人口），经济户口7802余户。',
    photo: [{
      name: '高强',
      icon: 'nfs/1高强.jpg'
    }, {
      name: '陈宇峰',
      icon: 'nfs/2陈宇峰.jpg'
    }, {
      name: '3顾玲燕',
      icon: 'nfs/3顾玲燕.jpg'
    }, {
      name: '应辉',
      icon: 'nfs/应辉.jpg'
    }, {
      name: '杨建云',
      icon: 'nfs/杨建云.jpg'
    }, {
      name: '林辉',
      icon: 'nfs/林辉.jpg'
    }, {
      name: '泮洪华',
      icon: 'nfs/泮洪华.jpg'
    }, {
      name: '王俊彪',
      icon: 'nfs/王俊彪.jpg'
    }, {
      name: '王光久',
      icon: 'nfs/王光久.jpg'
    }, {
      name: '蒋璐鹭',
      icon: 'nfs/蒋璐鹭.jpg'
    }, {
      name: '陈丽娟',
      icon: 'nfs/陈丽娟.jpg'
    }, {
      name: '陈华新',
      icon: 'nfs/陈华新.jpg'
    }]
  },
  {
    name: '下各所',
    phone: '0576-87611241',
    description: '下各市场监督管理所于2014年2月底设立，前身为下各工商行政管理所，座落于仙居县下各镇铁山路12号。同时挂下各市场监督管理所、下各工商行政管理所、下各食品药品监督管理所、下各市场监督管理执法中队、下各质量技术监督所五块牌子，下设二个中队和综合办公室，现有干部职工9名，管辖下各、双庙、朱溪、大战两镇两乡，辖区总面积为463.6平方公里，158个行政村，辖区人口11万。辖区内有经济户口2541户，其中食品药品相关经济主体610家。',
    photo: [
      {
        name: '郭盛',
        icon: 'xgs/郭盛.jpg'
      },
      {
        name: '陈奕兆',
        icon: 'xgs/陈奕兆(1).jpg'
      },
      {
        name: '余芝颖',
        icon: 'xgs/余芝颖.jpg'
      },
      {
        name: '吴连艳',
        icon: 'xgs/吴连艳.jpg'
      },
      {
        name: '周敏',
        icon: 'xgs/周敏.jpg'
      },
      {
        name: '应才勇',
        icon: 'xgs/应才勇.jpg'
      },
      {
        name: '应首贵',
        icon: 'xgs/应首贵.jpg'
      },
      {
        name: '徐敏红',
        icon: 'xgs/徐敏红.jpg'
      },
      {
        name: '陈鸯鸯',
        icon: 'xgs/陈鸯鸯.jpg'
      },
    ]
  },
  {
    name: '白塔分局',
    phone: '0576-87011010',
    description: '白塔市场监督管理分局现监管服务白塔镇、田市镇、淡竹乡、皤滩乡行政区域，面积490平方公里，行政村95个，人口9.7万余人。目前，我所有正式干部共12名，今年新进公务员4名，本科以上学历9人。本所先后参与全系统多项创建活动，荣获“全国工商行政管理系统先进工商所”、浙江省“群众满意基层站所（服务窗口）创建工作”先进单位、省“红盾风采文明规范工商所”、 省二星、三星、四星级文明规范工商所（2007、2010、2012）、台州市“群众满意基层站所（办事窗口）创建工作”先进单位、台州市“十佳基层工商所”、台州市先进集体（2006、2009、2010、2012）、仙居县“学习型党组织建设先进单位”、县级文明单位等荣誉。',
    photo: [{
      name: '王志文',
      icon: 'bts/1王志文.jpg'
    }, {
      name: '杨斌',
      icon: 'bts/2杨斌.jpg'
    }, {
      name: '应君怡',
      icon: 'bts/3应君怡.jpg'
    }, {
      name: '陈齐',
      icon: 'bts/4陈齐.jpg'
    }, {
      name: '陈辉',
      icon: 'bts/5陈辉.jpg'
    }, {
      name: '沈焕来',
      icon: 'bts/6沈焕来.jpg'
    }, {
      name: '应肖华',
      icon: 'bts/7应肖华.jpg'
    }, {
      name: '俞杨轮',
      icon: 'bts/8俞杨轮.jpg'
    }, {
      name: '陈飞融',
      icon: 'bts/9陈飞融.jpg'
    }, {
      name: '陈科志',
      icon: 'bts/10陈科志.jpg'
    }, {
      name: '张灵巧',
      icon: 'bts/11张灵巧.jpg'
    }, {
      name: '潘怡廷',
      icon: 'bts/12潘怡廷.jpg'
    }]
  },
];
class MarketInstitutionNavigation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      zoom: 16, //地图级别
      organise: [],
      selectedOrg: {},
      loading: false,
      visible: false,
      modalData: {}
    };
    this.initOrganise = ::this.initOrganise;
    this.loadDeptInfo = ::this.loadDeptInfo;
  }

  componentDidMount() {
    //经纬度地图显示；
    this.map = new T.Map('mapContent');
    this.getCenter();
    this.initOrganise();
  }
  getCenter() {
    this.Gmap = new AMap.Map('container111', {
      resizeEnable: true
    });
    this.Gmap.plugin('AMap.Geolocation', () => {
      this.geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
        buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        buttonPosition: 'RB'
      });
      this.Gmap.addControl(this.geolocation);
      this.geolocation.getCurrentPosition();
      AMap.event.addListener(this.geolocation, 'complete', (res) => {
        const json = GCJ_TO_GPS84(res.position.getLat(), res.position.getLng());
        console.log(json);
        window.lng = json.lng;
        window.lat = json.lat;
        // initial 天地图
        this.initMap();
        this.onLoad();
        this.initList();
      });//返回定位信息
      AMap.event.addListener(this.geolocation, 'error', (msg) => {
        console.log('获取当前位置error', msg);
        window.lng = mapConfig.longitude;
        window.lat = mapConfig.latitude;
        // initial 天地图
        this.initMap();
        this.onLoad();
        this.initList();
      });      //返回定位出错信息
    });
  }
  initOrganise() {
    const api = new Api({
      method: 'GET',
      path: '/depts/level',
      success: (res) => {
        this.setState({
          organise: res
        });
        this.loadDeptInfo(res);
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  loadDeptInfo(data) {
    const self = this;
    for (let i = 0; i < data.length; i++) {
      const icon1 = new T.Icon({ iconUrl: 'images/icon_business.png', iconSize: new T.Point(40, 40), iconAnchor: new T.Point(20, 40) });
      //向地图上添加自定义标注
      const markerBusi = new T.Marker(new T.LngLat(data[i].longitude, data[i].latitude), { icon: icon1 });
      self.map.addOverLay(markerBusi);
      //add title
      // icon click
      markerBusi.addEventListener('click', () => {
        this.map.clearOverLays();
        this.loadDeptInfo(this.state.organise);
        this.onLoad();
        const organiseInfo = OrganiseInfo.filter(organise => data[i].name.indexOf(organise.name) > -1)[0];
        if (organiseInfo && this.isVertical) {
          let photoInfo = '';
          for (let p = 0, len = organiseInfo.photo.length; p < len; p++) {
            const photoItem = `
            <div class="info-window-pp">
                            <img class="pp-image" src=${`images/organisePeople/${organiseInfo.photo[p].icon}`} />
                            <div class="pp-name">${organiseInfo.photo[p].name}</div>
                          </div>`;
            photoInfo += photoItem;
          }
          const infoContent = `<ul class="info-pp">
                        <li>名称：${data[i].name || ''}</li>
                        <li>地址：${data[i].address || ''}</li>
                        <li>负责人：${data[i].leader || ''}</li>
                        <li>办公电话：${organiseInfo.phone || ''}</li>
                        <li>机构简介: ${organiseInfo.description || ''}</li>
                        <li class="pp-row">
                          ${photoInfo}
                        </li>
                        </ul>`;
          const infoMinWidth = this.isVertical ? 600 : 600;
          this.infoWin = new T.InfoWindow(infoContent, { minWidth: infoMinWidth, autoPan: true });
          const lnglat = new T.LngLat(data[i].longitude, data[i].latitude);
          this.map.panTo(new T.LngLat(data[i].longitude, data[i].latitude), this.map.getZoom());
          this.infoWin.setLngLat(lnglat);
          this.infoWin.setOffset([0, 336]);
        } else if (organiseInfo && !this.isVertical) {
          this.setState({
            visible: true,
            modalData: { ...organiseInfo, ...data[i] },
          });
        } else {
          const infoContent = `<ul >
                        <li>名称：${data[i].name || ''}</li>
                        <li>地址：${data[i].address || ''}</li>
                        <li>负责人：${data[i].leader || ''}</li>
                        <li>联系方式：${data[i].phone || ''}</li>
                        </ul>`;
          this.infoWin = new T.InfoWindow(infoContent);
          const lnglat = new T.LngLat(data[i].longitude, data[i].latitude);
          this.map.panTo(new T.LngLat(data[i].longitude, data[i].latitude), this.map.getZoom());
          this.infoWin.setLngLat(lnglat);
          this.infoWin.setOffset([0, -36]);
        }
        //向地图上添加信息窗口
        this.map.addOverLay(this.infoWin);
      }, false);
    }
  }
  initMap() {
    //创建缩放平移控件对象
    const control = new T.Control.Zoom();
    //添加缩放平移控件
    control.setPosition(T_ANCHOR_BOTTOM_RIGHT);
    this.map.addControl(control);
    //双击放大地图；
    this.map.enableDoubleClickZoom();
    //地图滚轮缩放；
    this.map.enableScrollWheelZoom();
    //地图惯性拖拽；
    this.map.enableInertia();
    //创建比例尺控件对象
    const scale = new T.Control.Scale();
    //添加比例尺控件
    this.map.addControl(scale);
    //设置显示地图的中心点和级别
    this.map.centerAndZoom(new T.LngLat(window.lng, window.lat), this.state.zoom);
  }
  initList() {
    //路线初始化
    const config = {
      policy: 0,
      onSearchComplete: this.searchResult.bind(this)
    };
    this.drivingRoute = new T.DrivingRoute(this.map, config);
  }
  onLoad() {
    //先清除地图覆盖物，在显示
   // this.clearAll();
    //创建我的位置标注对象
    //添加我的位置备注信息；
    const lnglat = new T.LngLat(window.lng, window.lat);
    const newIcon = new T.Icon({ iconUrl: 'images/icon_map.png', iconSize: new T.Point(34, 42), iconAnchor: new T.Point(17, 42) });
    this.marker = new T.Marker(lnglat, { icon: newIcon });
    //向地图上添加标注
    this.map.addOverLay(this.marker);
    //创建信息窗口对象
    this.infoWin = new T.InfoWindow();
    this.infoWin.setLngLat(lnglat);
    this.infoWin.setOffset([0, -42]);
    //设置信息窗口要显示的内容
    this.infoWin.setContent('您的位置');
    //向地图上添加信息窗口
    this.map.addOverLay(this.infoWin);
  }

  clearAll() {
    this.map.clearOverLays();
  }
  searchBtnResult() {
    console.log('click search');
    const { selectedOrg, loading } = this.state;
    if (selectedOrg.longitude === window.lng && selectedOrg.latitude === window.lat) {
      return;
    }
    if (loading) {
      return;
    }
    if (this.Track) {
      this.Track.clear();
    }
    this.map.clearOverLays();
    this.onLoad();
    this.initOrganise(this.state.organise);
    this.map.panTo(new T.LngLat(selectedOrg.longitude, selectedOrg.latitude), this.map.getZoom());
    const startLngLat = new T.LngLat(window.lng, window.lat);
    const endLngLat = new T.LngLat(selectedOrg.longitude, selectedOrg.latitude);
    //路线搜索
    this.setState({ loading: true });
    this.drivingRoute.search(startLngLat, endLngLat);
    setTimeout(() => {
      this.setState({ loading: false });
    }, 5000);
  }
  searchResult(result) {
    console.log('search complete');
    this.setState({ loading: false });
    const routes = result.getNumPlans();
    for (let i = 0; i < routes; i++) {
      //获得单条方案结果对象
      const plan = result.getPlan(i);
      this.createRoute(plan.getPath());
    }
  }
  //画track
  createRoute(lnglats) {
    this.Track = new T.CarTrack(this.map, {
      interval: 20,
      speed: 10,
      dynamicLine: true,
      Datas: lnglats,
      carstyle: { display: false, iconUrl: '', width: 0, height: 0 },
      polylinestyle: { color: '#1480FF', width: 7, opacity: 0.9 }
    });
  }
  handleOrganiseChange(value) {
    const { organise, loading } = this.state;
    if (loading) {
      return;
    }
    const selectOrganise = organise.filter(item => item.name === value);
    console.log(selectOrganise);
    this.setState({
      selectedOrg: selectOrganise.length > 0 ? selectOrganise[0] : {}
    });
  }
  render() {
    const { organise, visible, modalData } = this.state;
    console.log(modalData);
    const { mode } = this.props;
    this.isVertical = BROWSER_MODE.isVertical(mode);
    if (this.isVertical) {
      return (
        <div className="v-map-container-project">
          <div className="main-map" >
            <div className="map-header" >
              <TitleButton
                title="机构导航"
              />
            </div >
            <div className="map" >
              <div id="mapContent" >
                <div className="search">
                  <div>
                    <div className="begin" >
                      <Input prefix={<div className="point green" />} placeholder="您的位置" disabled />
                    </div>
                    <div className="end">
                      <Select style={{ width: 229 }} onChange={this.handleOrganiseChange.bind(this)} defaultActiveFirstOption={false}>
                        {
                          organise.length > 0 ? organise.map(item => (
                            <Option value={item.name} key={item.id}>{item.name}</Option>
                          )) : null
                        }
                      </Select>
                      <span className="dot" />
                    </div>
                  </div>
                  <div onClick={this.searchBtnResult.bind(this)} className="search-btn">
                    <Spin size="small" spinning={this.state.loading} />
                    搜索
                  </div>
                </div>
              </div>
            </div >
          </div >
        </div >
      );
    }
    return (
      <div className="map-container-project" >
        <div className="main-map" >
          <TitleButton
            title="机构导航"
          />
          <div className="map" >
            <div id="mapContent" >
              <div className="search">
                <div className="left-wrap">
                  <Input prefix={<div className="point green" />} placeholder="您的位置" disabled />
                  <div className="end-wrap">
                    <Select style={{ width: 320 }} onChange={this.handleOrganiseChange.bind(this)} defaultActiveFirstOption={false}>
                      {
                        organise.length > 0 ? organise.map(item => (
                          <Option value={item.name} key={item.id}>{item.name}</Option>
                        )) : null
                      }
                    </Select>
                    <span className="point dot" />
                  </div>
                </div>
                <div onClick={this.searchBtnResult.bind(this)} className="search-btn">
                  <Spin size="small" spinning={this.state.loading} />
                  搜索
                </div>
              </div>
            </div>
          </div >
        </div >
        <Modal
          visible={visible}
          footer={null}
          onCancel={() => { this.setState({ visible: false }); }}
          className="h-modal"
          width={600}
        >
          <div className="row">
            <span>名称：</span><span>{modalData.name || ''}</span>
          </div>
          <div className="row">
            <span>地址：</span><span>{modalData.address || ''}</span>
          </div>
          <div className="row">
            <span>负责人：</span><span>{modalData.leader || ''}</span>
          </div>
          <div className="row">
            <span>办公电话：</span><span>{modalData.phone || ''}</span>
          </div>
          <div className="row">
            <span>机构简介：</span><span>{modalData.description || ''}</span>
          </div>
          <div className="pp-row">
            {
              modalData.photo ? modalData.photo.map(item => (
                <div className="info-window-pp" key={item.name}>
                  <img className="pp-image" src={`images/organisePeople/${item.icon}`} />
                  <div className="pp-name">{item.name}</div>
                </div>
              )) : ''
            }
          </div>
        </Modal>
      </div >
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.webReducer
  };
}
export default connect(mapStateToProps)(MarketInstitutionNavigation);
